import 'dart:async';
import 'dart:ui';
import 'package:chop/Model/address_entity.dart';
import 'package:chop/common/SPUtils.dart';
import 'package:chop/common/StringUtils.dart';
import 'package:chop/common/configs.dart';
import 'package:chop/view/home/do_job/Pickup.dart';
import 'package:chop/view/home/do_job/Pickupaddress.dart';
import 'package:chop/view/home/place_an_order/Delivery_order.dart';
import 'package:chop/view/home/place_an_order/Pickup_order.dart';
import 'package:chop/view/login/login.dart';
import 'package:chop/widgets/TextSizeWidget.dart';
import 'package:chop/widgets/ToastWidget.dart';
import 'package:chop/widgets/appBar.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:geolocator/geolocator.dart';
import 'package:get/get.dart';
import 'package:google_map_polyline/google_map_polyline.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:loading_animations/loading_animations.dart';

import 'Personal_center/Personal_center.dart';
import 'bottom_tab_item_Buying.dart';

import 'do_job/Delivery.dart';
import 'do_job/Deliveryaddress.dart';

// ignore: camel_case_types
class homePage extends StatefulWidget {
  @override
  _homePageState createState() => _homePageState();
}

// ignore: camel_case_types
class bottomItem {
  final String title;
  final Icon icon;

  // ignore: sort_constructors_first
  bottomItem({this.title, this.icon});
}

// ignore: camel_case_types
class _homePageState extends State<homePage>
    with AutomaticKeepAliveClientMixin {
  bool isNetworkNotBad = false;
  GoogleMapPolyline googleMapPolyline =
      GoogleMapPolyline(apiKey: Configs.API_KEY);

  Widget getBody(BuildContext context) {
    if (isNetworkNotBad) {
      print("wan");
      return _buildBody(context);
    } else {
      print("正在加载");
      return Center(child: LoadingJumpingLine.square());
    }
  }

  TextEditingController _deliveryBeginController = TextEditingController();
  TextEditingController _deliveryEndController = TextEditingController();
  TextEditingController _pickupBeginController = TextEditingController();
  TextEditingController _pickupEndController = TextEditingController();
  TextEditingController _buyController = TextEditingController();

  AdrEntityData deliveryBegin;
  AdrEntityData deliveryEnd;
  AdrEntityData pickupBegin;
  AdrEntityData pickupEnd;

  TabController _tabController;
  Position position;

  // 获取当前定位
  getPosition() async {
    GeolocationStatus geolocationStatus =
        await Geolocator().checkGeolocationPermissionStatus();
    if (geolocationStatus.value == 2) {
      print("adfa");
      position = await Geolocator().getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
      getU();
    } else {
      Toast.toast(context, msg: "请开启gps定位权限", bgColor: Colors.redAccent);
    }
    print("---------------->定位权限：${geolocationStatus.value}");

  }

  @override
  void initState() {
    getPosition();
    _tabController = TabController(length: 3, vsync: ScaffoldState())
      ..addListener(() {
        _currentIndex = _tabController.index;
      });
    // TODO: implement initState
    super.initState();
  }

  // 地图控制器
  Completer<GoogleMapController> _controller = Completer();

  // 起始定位
  CameraPosition _kGooglePlex;

  //选项卡浮动高度
  double bottomItemHeight = 50;

  // 底部选项卡是否展示
  bool isBottomShow = true;

  // 当前底部选项卡索引
  int _currentIndex = 0;

  //底部选项卡
  List<bottomItem> _tabber = [
    bottomItem(title: "Delivery", icon: Icon(Icons.directions_run)),
    bottomItem(title: "Pickup", icon: Icon(Icons.transfer_within_a_station)),
    bottomItem(title: "Buying", icon: Icon(Icons.shopping_cart)),
  ];

  Widget _buildBody(BuildContext context) {
    return Container(
        height: MediaQuery.of(context).size.height,
        child: GoogleMap(
          myLocationEnabled: true,
          myLocationButtonEnabled: false,
          initialCameraPosition: _kGooglePlex,
//              onMapCreated: (GoogleMapController controller) {
//                _controller.complete(controller);
//              },
        ));
  }

  @override
  // ignore: must_call_super
  Widget build(BuildContext context) {
    final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
    ScreenUtil.init(context);
    return Scaffold(
      key: _scaffoldKey,
      appBar: BaseViewBar(
        childView: BaseTitleBar(
          "Chop跑腿",
          leftIcon: Icons.account_box,
          leftClick: () {
            Get.to(Persinal());
          },
        ),
        preferredSize: Size.fromHeight(65.0),
      ),
      body: DefaultTabController(
        length: 3,
        initialIndex: _currentIndex,
        child: Stack(
          children: <Widget>[
            getBody(context),
            Positioned(
                bottom: 70,
                width: MediaQuery.of(context).size.width,
                height: 170,
                child: Container(
                    margin: EdgeInsets.only(left: 5, right: 5),
                    child: TabBarView(
                      controller: _tabController,
                      children: [
                        getBottomItem(0, _deliveryBeginController,
                            _deliveryEndController, deliveryBegin, deliveryEnd),
                        getBottomItem(1, _pickupBeginController,
                            _pickupEndController, pickupBegin, pickupEnd),
                        getBuyingItem(_buyController),
                      ],
                    ))),
            Positioned(
                bottom: 0,
                height: 70,
                width: MediaQuery.of(context).size.width,
                child: Container(
                  color: Colors.white,
                  child: TabBar(
                      indicatorColor: Colors.transparent,
                      labelColor: Colors.blue,
                      unselectedLabelColor: Colors.blue[200],
                      onTap: (index) {
                        _currentIndex = index;
                      },
                      controller: _tabController,
                      tabs: _tabber.map((bottomItem item) {
                        return Tab(
                            icon: item.icon, child: FixedSizeText(item.title));
                      }).toList()),
                ))
          ],
        ),
      ),
    );
  }

  // 下单事件
  void orderCallBack(int index) {
    if (index == 0) {
      if (deliveryBegin != null && deliveryEnd != null) {
        Get.to(Delivery_order(
          begin: deliveryBegin,
          end: deliveryEnd,
        ));
      } else {
        Toast.toast(context, msg: "请填写完整订单信息", position: ToastPostion.bottom);
      }
    } else {
      if (pickupBegin != null && pickupEnd != null) {
        Get.to(Pickup_order(
          begin: pickupBegin,
          end: pickupEnd,
        ));
      } else {
        Toast.toast(context, msg: "请填写完整订单信息", position: ToastPostion.bottom);
      }
    }
    print("点击了立即下单");
  }

  /**
   * 规划路线
   */
  getU({LatLng destination}) async {
    setState(() {
      //改变网络请求状态
      isNetworkNotBad = true;
      //设置初始位置
      _kGooglePlex = CameraPosition(
        target: LatLng(position.latitude, position.longitude),
        zoom: 14.4746,
      );
    });
  }

  @override
  bool get wantKeepAlive => true;

  //构建底部选项卡
  Widget getBottomItem(
    index,
    TextEditingController _beginController,
    TextEditingController _endController,
    AdrEntityData begin,
    AdrEntityData end,
  ) {
    return Container(
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(17),

          ///圆角
          border: Border.all(color: Colors.white, width: 1),

          ///边框颜色、宽
          color: Colors.white,
        ),
        padding: EdgeInsets.all(10),
        child: Row(
          children: <Widget>[
            Expanded(
              child: Container(
                padding: EdgeInsets.fromLTRB(25, 6, 10, 0),
                alignment: Alignment.bottomLeft,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Column(
                      children: <Widget>[
                        Row(
                          children: <Widget>[
                            FixedSizeText(
                              "${index == 0 ? '● 从哪里发货:' : '● 从哪里取件:'}",
                              textAlign: TextAlign.left,
                              style: TextStyle(
                                  color: Colors.black,
                                  fontSize: ScreenUtil().setSp(36),
                                  height: 1,
                                  fontWeight: FontWeight.w800),
                            )
                          ],
                        ),
                        TextField(
                          controller: _beginController,
                          cursorWidth: 10,
                          decoration: InputDecoration(
                              hintText:
                                  "${index == 0 ? '请点击选择发货地址' : '请点击选择取件地址'}",
                              border: InputBorder.none),
                          readOnly: true,
                          style: TextStyle(fontSize: ScreenUtil().setSp(25)),
                          onTap: () async {
                            if (index == 0) {
                              deliveryBegin = await Get.to(Delivery_job());
                              _beginController.text = deliveryBegin == null
                                  ? null
                                  : deliveryBegin.remark;
                            } else {
                              pickupBegin = await Get.to(Pickup_job());
                              _beginController.text = pickupBegin == null
                                  ? null
                                  : pickupBegin.remark;
                            }
                          },
                        ),
                      ],
                    ),
                    Column(
                      children: <Widget>[
                        Row(
                          children: <Widget>[
                            FixedSizeText(
                              "${index == 0 ? '● 您要送到哪里:' : '● 您要送到哪里:'}",
                              style: TextStyle(
                                  fontSize: ScreenUtil().setSp(36),
                                  color: Colors.black,
                                  height: 2,
                                  fontWeight: FontWeight.w800),
                            )
                          ],
                        ),
                        TextField(
                          controller: _endController,
                          decoration: InputDecoration(
                              hintText:
                                  "${index == 0 ? '请点击选择送达地址' : '请点击选择送达地址'}",
                              border: InputBorder.none),
                          style: TextStyle(fontSize: ScreenUtil().setSp(25)),
                          readOnly: true,
                          onTap: () async {
                            String phone = await SPUtils.get("phone");
                            if(StringUtils.isNull(phone)){
                              Toast.toast(context,msg: "请先进行登陆",bgColor: Colors.redAccent,position: ToastPostion.bottom);
                              Get.to(LoginPage());
                            }else{
                              if (index == 0) {
                                deliveryEnd = await Get.to(Deliveryaddress_job());
                                _endController.text = deliveryBegin == null
                                    ? null
                                    : deliveryEnd.remark;
                              } else {
                                pickupEnd = await Get.to(Pickupaddress_job());
                                _endController.text =
                                pickupEnd == null ? null : pickupEnd.remark;
                              }
                            }
                          },
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
            Expanded(
              child: Container(
                height: 80,
                child: RaisedButton(
                  child: FixedSizeText("立即下单", style: TextStyle(fontSize: 14)),
                  color: Colors.blue,
                  textColor: Colors.white,
                  elevation: 20,
                  splashColor: Colors.blue,
                  shape: CircleBorder(side: BorderSide(color: Colors.white)),
                  onPressed: () {
                    orderCallBack(index);
                  },
                ),
              ),
            )
          ],
        ));
  }
}
